package com.ls.lserp.modules.material.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.entity.MaterialOutInbound;
import com.ls.lserp.modules.material.service.MaterialInboundService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: CustomerController
 * @Description: 
 * 
 * @author 刘晓彤
 * @date 2017年3月16日 
 *
 */


@Controller
@RequestMapping(value = "${adminPath}/material/inbound/")
public class MaterialInboundController extends BaseController {

	
	@Autowired
	private MaterialInboundService materialInboundService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public MaterialOutInbound get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return materialInboundService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new MaterialOutInbound();
		}
	}
	
	
	
	/**
	 * 进入一览画面
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:view")
	@RequestMapping(value = { "" })
	public String list(MaterialOutInbound materialOutInbound, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		//返回页面地址
		return "modules/material/materialInbound";

	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param materialOutInbound
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("material:inbound:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(MaterialOutInbound materialOutInbound, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "materialInbound");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 入库单号
		searchParam.append("&inventoryRequestNo=");
		searchParam.append(materialOutInbound.getInventoryRequestNo());
		// 入库类别
		searchParam.append("&inventoryCategory=");
		searchParam.append(materialOutInbound.getInventoryCategory());
		// 客户/供货商名称
		searchParam.append("&venderName=");
		searchParam.append(materialOutInbound.getVenderName());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(materialOutInbound.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(materialOutInbound.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(materialOutInbound.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<MaterialOutInbound> page = materialInboundService.findList(new Page<MaterialOutInbound>(request, response),materialOutInbound);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("materialInbounds", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("materialInbound.ftl"), map);
		listMap.put("materialInbound", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	    * 保存信息
	    * @param materialOutInbound
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("material:inbound:edit")
	   @RequestMapping(value = "saveDetail")
	   @ResponseBody
	   public String saveDetail(MaterialOutInbound materialOutInbound, HttpServletResponse response) throws ResourceException {
		   
	   	   // 保存入库申请
		   materialInboundService.saveDetail(materialOutInbound);
	   	
	   	   // 保存成功返回提示信息
	       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
	   }
	   /**
	    * 保存信息
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("material:inbound:edit")
	   @RequestMapping(value = "saveQuantity")
	   @ResponseBody
	   public String saveQuantity(MaterialOutInbound materialOutInbound, HttpServletResponse response) throws ResourceException {
		   
	   	   // 保存入库申请
		   materialInboundService.saveQuantity(materialOutInbound);
	   	
	   	   // 保存成功返回提示信息
	       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
	   }
	/**
	    * 进入查看页面
	    * @param materialOutInbound
	    * @param model
	    * @return
	    */
	   @RequiresPermissions("material:inbound:view")
	   @RequestMapping(value = "show")
	   public String show(MaterialOutInbound materialOutInbound, Model model) {
		   
	   	   // 查找入库申请明细
		   List<MaterialOutInbound> resultRequestList = materialInboundService.findRequestDetailsList(materialOutInbound);
		   materialOutInbound.setRequestDetailsList(resultRequestList);
	   	
	       // 将查询结果赋值mvc model层返回jsp页面
	       model.addAttribute("materialOutInbound", materialOutInbound);
	       
	       // 返回页面地址
	       return "modules/material/materialInboundShow";
	   }
	/**
	 * 创建物料入库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:view")
	@RequestMapping(value = {"materialDetailList"})
	public String materialDetailList(MaterialOutInbound materialOutInbound, HttpServletRequest request, HttpServletResponse response,
			Model model){
		materialOutInbound.setRequestDetailsList(materialInboundService.findInventoryMaterialDetailList(materialOutInbound));
		model.addAttribute("materialOutInbound",materialOutInbound);
		return "modules/material/materialInDetail";
	}
	/**
	 * 创建物料入库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:view")
	@RequestMapping(value = {"detailCreate"})
	public String detailCreate(MaterialOutInbound materialOutInbound, HttpServletRequest request, HttpServletResponse response,
			Model model){
		materialOutInbound.setWarehouseList(materialInboundService.findWarehouseList(materialOutInbound));
		model.addAttribute("materialOutInbound",materialOutInbound);
		return "modules/material/materialInDetailCreate";
	}
	/**
	 * 创建物料入库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:view")
	@RequestMapping(value = {"findRack"})
	public String findRack(MaterialOutInbound materialOutInbound, HttpServletRequest request, HttpServletResponse response,
			Model model){
		materialOutInbound.setRackList(materialInboundService.findRackList(materialOutInbound));
		model.addAttribute("materialOutInbound",materialOutInbound);
		return "modules/material/materialInDetailCreate";
	}
	/**
	 * 创建物料入库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:edit")
	@RequestMapping(value = {"changeStatus"})
	@ResponseBody
	public String changeStatus(MaterialOutInbound materialOutInbound,HttpServletResponse response,Model model){
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		materialInboundService.changeStatus(materialOutInbound);
		return renderString(response, listMap);
	}
	
	/**
	 * 更新面料库存预警状态
	 * 
	 * @return
	 */
	@RequiresPermissions("material:inbound:edit")
	@RequestMapping(value = {"updateStatus"})
	@ResponseBody
	public String updateStatus(String materialId, String venderId ,HttpServletResponse response,Model model){
		String flag = "false";
		try {
			materialInboundService.updateStatus(materialId,venderId);
			flag = "true";
		} catch (Exception e) {
			//异常打印log
			logger.error(e.getMessage(),e);
		}
		return renderString(response, flag);
	}
	
}
